import { GameState, SavedGame } from '../types';

const STORAGE_KEY = 'monopoly-game-state';
const VERSION = '1.0.0';

/**
 * 序列化游戏状态
 */
export function serializeGameState(gameState: GameState): string {
  try {
    return JSON.stringify(gameState);
  } catch (error) {
    console.error('序列化失败:', error);
    throw new Error('无法序列化游戏状态');
  }
}

/**
 * 反序列化游戏状态
 */
export function deserializeGameState(data: string): GameState {
  try {
    return JSON.parse(data);
  } catch (error) {
    console.error('反序列化失败:', error);
    throw new Error('无法反序列化游戏状态');
  }
}

/**
 * 计算校验和
 */
export function calculateChecksum(data: string): string {
  let hash = 0;
  for (let i = 0; i < data.length; i++) {
    const char = data.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash; // Convert to 32bit integer
  }
  return hash.toString(36);
}

/**
 * 验证校验和
 */
export function verifyChecksum(data: string, checksum: string): boolean {
  return calculateChecksum(data) === checksum;
}

/**
 * 保存游戏到本地存储
 */
export function saveGameToStorage(gameState: GameState): boolean {
  try {
    const serialized = serializeGameState(gameState);
    const checksum = calculateChecksum(serialized);

    const savedGame: SavedGame = {
      version: VERSION,
      timestamp: Date.now(),
      gameState,
      checksum,
    };

    localStorage.setItem(STORAGE_KEY, JSON.stringify(savedGame));
    return true;
  } catch (error) {
    console.error('保存游戏失败:', error);
    return false;
  }
}

/**
 * 从本地存储加载游戏
 */
export function loadGameFromStorage(): GameState | null {
  try {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (!saved) {
      return null;
    }

    const savedGame: SavedGame = JSON.parse(saved);

    // 验证版本
    if (savedGame.version !== VERSION) {
      console.warn('游戏版本不匹配');
      return null;
    }

    // 验证校验和
    const serialized = serializeGameState(savedGame.gameState);
    if (!verifyChecksum(serialized, savedGame.checksum)) {
      console.error('数据校验失败');
      return null;
    }

    return savedGame.gameState;
  } catch (error) {
    console.error('加载游戏失败:', error);
    return null;
  }
}

/**
 * 检查是否有保存的游戏
 */
export function hasSavedGame(): boolean {
  return localStorage.getItem(STORAGE_KEY) !== null;
}

/**
 * 清除保存的游戏
 */
export function clearSavedGame(): void {
  localStorage.removeItem(STORAGE_KEY);
}

/**
 * 获取保存游戏的信息
 */
export function getSavedGameInfo(): { timestamp: number; version: string } | null {
  try {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (!saved) {
      return null;
    }

    const savedGame: SavedGame = JSON.parse(saved);
    return {
      timestamp: savedGame.timestamp,
      version: savedGame.version,
    };
  } catch (error) {
    return null;
  }
}

/**
 * 导出游戏数据（用于分享或备份）
 */
export function exportGameData(gameState: GameState): string {
  const savedGame: SavedGame = {
    version: VERSION,
    timestamp: Date.now(),
    gameState,
    checksum: calculateChecksum(serializeGameState(gameState)),
  };

  return btoa(JSON.stringify(savedGame)); // Base64编码
}

/**
 * 导入游戏数据
 */
export function importGameData(data: string): GameState | null {
  try {
    const decoded = atob(data); // Base64解码
    const savedGame: SavedGame = JSON.parse(decoded);

    // 验证校验和
    const serialized = serializeGameState(savedGame.gameState);
    if (!verifyChecksum(serialized, savedGame.checksum)) {
      console.error('导入数据校验失败');
      return null;
    }

    return savedGame.gameState;
  } catch (error) {
    console.error('导入游戏失败:', error);
    return null;
  }
}
